<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use backend\controllers\BaseController;
use backend\models\LoginForm;
use yii\filters\VerbFilter;
use common\models\Log;
use common\models\Report;
use common\models\Report_new;
use common\models\OverReport;
use yii\mongodb\Query;
use yii\mongodb\Collection;
use backend\models\AdverMongo;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    
    /**
     * @inheritdoc
     */
    CONST LOG_TYPE_STEP1 = 1;
    CONST LOG_TYPE_STEP2 = 2;
    CONST LOG_TYPE_STEP3 = 3;
    CONST LOG_TYPE_STEP4 = 4;
    CONST LOG_TYPE_STEP5 = 5;
    CONST LOG_TYPE_STEP6 = 6;
    CONST LIMIT_TIME = 300;
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }


    /*
     * 凌晨轮询是否有未处理完的文件和为下载完成的文件
     */
    public function actionCheck()
    {
        $error = file_get_contents('error_copy.log');
        $files = explode("\n", $error);
        if($files)
        {
            unlink('error_copy.log');
        }
        foreach($files as $v)
        {
            if(!@copy('http://192.168.108.179:85/soft/'.$v,'./'.$v.'.txt'))
            {
                $errors= error_get_last();
                echo "COPY ERROR: ".$errors['type'];
                echo "<br />\n".$errors['message'];
                Log::save("test.txt\n",'error_copy.log');
            }
            else
            {
                $this->actionIndex($v);
            }
        }
    }

    public function actionTwo()
    {
        $handle = fopen('./bb.txt', "r");
        //解析文件
        while(!feof($handle)) {
            $t = json_decode(stream_get_line($handle, 1000, "\n"));
//            $request_id = $t->request_id;
//            $strategy_id = $t->strategy_id;
//            $company = $t->company;
//            $city = $t->city;
//            $line = $t->line;
//            $l_ping = $t->l_ping;
//            $company = $t->company;
//            $company = $t->company;
            if ($t->status) {
              //  AdverMongo::addAdver(['name'=>222, 'status' => $t->status, 'request_id' => $t->request_id]);
            }
        }

        $check_yuan = AdverMongo::findAdver();
        //原始表根据插入时间倒序循环
        foreach ($check_yuan as &$v) {
            if(isset($v['request_id']))
            {
                $data = AdverMongo::findNewAdver($v['request_id']);
                var_dump($data);
            }

//            $new_database = Report_new::find()->where(['request_id' => $v->request_id])->one();
        }
    }

    public function actionIndex($files = '')
    {
        //$error = error_get_last();
        // var_dump($error);
        /*if(!@copy('http://192.168.108.179:85/soft/test.txt','./test.txt'))
        {
            $errors= error_get_last();
            echo "COPY ERROR: ".$errors['type'];
            echo "<br />\n".$errors['message'];
            Log::save("test.txt\n",'error_copy.log');
        }else*/
        //{
//        $a = ['a' => 1, 'b' => ['c' => 2, 'd' => 3]];
//        file_put_contents('bb.txt',json_encode($a));die;
        $handle = fopen('./bb.txt', "r");
        //$contents = fread($handle, filesize ('./dou.txt'));
        $contents = '';
        //$contents = file_get_contents('dou.txt');
        //var_dump($contents);die;
//  解析文件
        while (!feof($handle)) {
            $t = json_decode(stream_get_line($handle, 1000, "\n"));
            if ($t->status) {
                $model = new Report_new();
                $model->request_id = $t->request_id;
                $model->strategy_id = $t->strategy_id;
                $model->ad_id = $t->ad_id;
                $model->company = $t->company;
                $model->city = $t->city;
                $model->line = $t->line;
                $model->l_ping = $t->l_ping;
                $model->datetime = $t->datetime;
                switch($t->data->type)
                {
                    case 1:
                        $model->status = 4;
                        break;
                    case 2:
                        $model->status = 5;
                        break;
                    case 3:
                        $model->status = 6;
                        break;
                    default:
                        $model->status = $t->status;
                        break;
                }
                $model->save();
            }
        }
        $check = Report_new::find()->all();
        foreach($check as $c)
        {
            //更新策略id
            if($c->status == self::LOG_TYPE_STEP2)
            {
                $c_model = Report_new::find()->where(['request_id' => $c->request_id])->all();
                foreach($c_model as $m)
                {
                    $m->strategy_id = $c->strategy_id;
                    $m->save();
                }
            }
        }
        unset($c);
        foreach($check as $c)
        {
            // 如果不是终端请求sdk,  而且策略id是空,去配置表查找
            if($c->strategy_id == '' && $c->status != self::LOG_TYPE_STEP1)
            {
                $over_model = OverReport::find()->where(['request_id' => $c->request_id, 'status' => 2])->one();
                if($over_model && $over_model->strategy_id != '')
                {
                    $m_c = Report_new::find()->where(['request_id' => $c->request_id])->all();
                    foreach($m_c as $m)
                    {
                        $m->strategy_id = $over_model->strategy_id;
                        $m->save();
                    }
                }
            }
        }
        unset($c);
        $check_yuan = Report_new::find()->where("strategy_id != 0")->groupBy('line, strategy_id')->all();
        //原始表根据插入时间倒序循环
        foreach ($check_yuan as $s) {
            $database = Report::find()->where(['line' => $s->line, 'strategy_id' => $s->strategy_id])->one();
            $request = !empty($database) ? $database->request_sum : 0;
            $response = !empty($database) ? $database->response_sum : 0;
            $success = !empty($database) ? $database->return_success_num : 0;
            $fail = !empty($database) ? $database->return_fail_num : 0;
            $no_picture = !empty($database) ? $database->return_no_picture : 0;

            $check = Report_new::find()->where(['line' =>$s->line, 'strategy_id' => $s->strategy_id])->all();
            foreach ($check as $v) {
//               $request_data = Report::find()->where(['request_id' => $v->request_id])->orderBy('status desc')->all();
                switch ($v->status) {
                    //请求终端
                    case self::LOG_TYPE_STEP1:
                        $over_model = OverReport::find()->where(['request_id' => $v->request_id, 'status' => 1])->one();
                        if (!$over_model) {
                            $request = $request + 1;
                            $over_model = new OverReport();
                            $over_model->request_id = $v->request_id;
                            $over_model->datetime = date('Y-m-d H:i:s');
                            $over_model->status = 1;
                            $over_model->save();
                        }
                       // var_dump($request);
                        break;
                    //百度返回,带策略id
                    case self::LOG_TYPE_STEP2:
                        $over_model = OverReport::find()->where(['request_id' => $v->request_id, 'status' => 2])->one();
                        if (!$over_model) {
                            $response += 1;
                            $over_model = new OverReport();
                            $over_model->request_id = $v->request_id;
                            $over_model->datetime = date('Y-m-d H:i:s');
                            $over_model->status = 2;
                            $over_model->strategy_id = $v->strategy_id;
                            $over_model->save();
                        }
                        break;
                    //响应数,sdk响应终端
//                    case self::LOG_TYPE_STEP3:
////                                $model = new Report();
////                                $model->deleteAll(['request_id' => $v->request_id]);
//                        break;
                    //展示成功或失败时,删除该request的广告
                    case self::LOG_TYPE_STEP4:
                        $over_model = OverReport::find()->where(['request_id' => $v->request_id, 'status' => 1])->one();
                        if ($over_model)
                        {
                            if ($v->datetime - $over_model->datetime > self::LIMIT_TIME) {
                                break;
                            }
                        }
                        $success += 1;
                        break;
                    case self::LOG_TYPE_STEP5:
                        $over_model = OverReport::find()->where(['request_id' => $v->request_id, 'status' => 1])->one();
                        if ($over_model)
                        {
                            if ($v->datetime - $over_model->datetime > self::LIMIT_TIME) {
                                break;
                            }
                        }
                        $fail += 1;
                        break;
                        case self::LOG_TYPE_STEP6:
                        $over_model = OverReport::find()->where(['request_id' => $v->request_id, 'status' => 1])->one();
                        if ($over_model) {
                            if ($v->datetime - $over_model->datetime > self::LIMIT_TIME) {
                                break;
                            }
                        }
                        $no_picture += 1;
                        break;
                }
            }
            if ($database) {
                $database->request_sum = $request;
                $database->response_sum = $response;
                $database->return_success_num = $success;
                $database->return_fail_num = $fail;
                $database->return_no_picture = $no_picture;
                $database->save();
            } else {
                $model_new = new Report();
                $model_new->ad_id = $s->ad_id;
                $model_new->strategy_id = $s->strategy_id;
                $model_new->company = $s->company;
                $model_new->city = $s->city;
                $model_new->line = $s->line;
                $model_new->l_ping = $s->l_ping;
                $model_new->line = $s->line;
                $model_new->datetime = $s->datetime;
                $model_new->request_sum = $request;
                $model_new->response_sum = $response;
                $model_new->return_success_num = $success;
                $model_new->return_fail_num = $fail;
                $model_new->return_no_picture = $no_picture;
                $model_new->save();
            }
        }
        // 删除处理过的数据
        Report_new::deleteAll('strategy_id is not null');
        fclose($handle);die;
        return $this->render('index');
    }


}
